package work.sajor.wechatpush.util;

import java.security.MessageDigest;

/**
 * @author huachengyu
 * @date 2018-08-23 21:46
 **/
public class Md5Util {

    /**
     * 加密-32位小写
     */
    public static String encrypt32(String encryptStr) {
        MessageDigest md5;
        try {
            md5 = MessageDigest.getInstance("MD5");
            byte[] md5Bytes = md5.digest(encryptStr.getBytes());
            StringBuilder hexValue = new StringBuilder();
            for (int i = 0; i < md5Bytes.length; i++) {
                int val = ((int) md5Bytes[i]) & 0xff;
                if (val < 16) {
                    hexValue.append("0");
                }
                hexValue.append(Integer.toHexString(val));
            }
            encryptStr = hexValue.toString();
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
        return encryptStr;
    }

    /**
     * 加密-16位小写
     */
    public static String encrypt16(String encryptStr) {
        return encrypt32(encryptStr).substring(8, 24);
    }

    /**
     * 加密-12位小写
     */
    public static String encrypt12(String encryptStr) {
        return encrypt32(encryptStr).substring(8, 20);
    }

    /**
     * 加密-8位小写
     */
    public static String encrypt8(String encryptStr) {
        return encrypt32(encryptStr).substring(8, 16);
    }
}
